import express from "express";
import MySQLPool from '../mysqlCreatePool';
import { upload } from "../uploadFile";
import { host } from "../server.config";
const router = express.Router();
const db = new MySQLPool();
// 获取奖品
router.get("/", async (req: any, res: any) => {
  const { id } = req.auth
  let user_id = req.query.userId ?? ''
  const sql = `SELECT * FROM reward WHERE user_id=${user_id}`;
  try {
    const [sqlres] = await db.queryRows(sql);
    res.send({
      code: 200,
      message: '',
      data: sqlres.map(t => ({ ...t, collect_ids: t.collect_ids ? t.collect_ids.includes(id + '') : false })),
    });
  } catch (e) {
    res.send({
      code: 201,
      message: e,
      data: null,
    });
  }
});
// 修改奖品
router.post('/update', upload.single('img'), async (req: any, res) => {
  const { id } = req.auth
  const reward = { ...req.body }
  let sql = '';
  if (!reward.id) {
    sql = `INSERT INTO reward (name,num,img,user_id,chang_time) VALUES ('${reward.name}', ${reward.num}, '${'/uploads/' + req.file?.filename}',${id},CONVERT(NOW(), CHAR));`
  }
  else {
    sql = 'update reward set '
    if (req.file && !reward.img?.includes(host)) {
      reward.img = req.file?.filename ? '/uploads/' + req.file?.filename : null
      sql += `img='${reward.img}',`
    }
    sql += `name='${reward.name}',num=${reward.num},chang_time=CONVERT(NOW(), CHAR) where id=${reward.id}`;
  }
  console.log(sql)
  try {
    const [sqlres] = await db.executeResult(sql)
    if (sqlres.affectedRows) {
      res.send({
        code: 200,
        message: '修改成功',
        data: true,
      });
    } else {
      res.send({
        code: 201,
        message: '修改失败',
        data: null,
      });
    }
  }
  catch (e) {
    res.send({
      code: 201,
      message: e,
      data: null,
    });
  }
})
// 删除奖品
router.delete('/del', async (req: any, res: any) => {
  const { id } = req.query
  try {
    const sql = `DELETE FROM reward WHERE id=${id};`
    const [sqlres] = await db.executeResult(sql)
    console.log(sqlres)
    if (sqlres.affectedRows) {
      res.send({
        code: 200,
        message: '删除成功',
        data: true,
      });
    } else {
      res.send({
        code: 201,
        message: '删除失败',
        data: null,
      });
    }
  }
  catch (e) {
    res.send({
      code: 201,
      message: e,
      data: null,
    });
  }
})
// 收藏奖品
router.get('/collect', async (req: any, res: any) => {
  const { id } = req.auth
  const { rewardId } = req.query
  try {
    const sql = `SELECT collect_ids FROM reward WHERE id=${rewardId};`
    const [sqlres] = await db.queryRows(sql)
    if (sqlres.length) {
      const ids = sqlres[0].collect_ids ? sqlres[0].collect_ids.split(',') : []
      let _ids = []
      let _sql = ''
      if (ids.includes(id + '')) _ids = ids.filter((t: string) => t !== (id + ''))
      else _ids = [...ids, id]
      _sql = `update reward set collect_ids='${_ids.join(',')}' WHERE id=${rewardId};`
      const [_sqlres] = await db.executeResult(_sql)
      if (_sqlres.affectedRows) {
        res.send({
          code: 200,
          message: '',
          data: null,
        })
      }
      else {
        res.send({
          code: 201,
          message: '',
          data: null,
        })
      }
    } else {
      res.send({
        code: 201,
        message: '没有当前奖品信息',
        data: null,
      })
    }
  } catch (e) {
    res.send({
      code: 201,
      message: e,
      data: null,
    })
  }
})
// 获取当前用户收藏的奖品
router.get('/collectList', async (req: any, res: any) => {
  const { id } = req.auth
  try {
    const sql = `SELECT * FROM reward WHERE collect_ids LIKE '%${id}%';`
    const [sqlres] = await db.queryRows(sql)
    res.send({
      code: 200,
      message: '',
      data: sqlres.map(t => ({ ...t, collect_ids: t.collect_ids.includes(id + '') })),
    });
  } catch (e) {
    res.send({
      code: 201,
      message: e,
      data: null,
    })
  }
})
// 兑换奖品
router.get('/exchange', async (req: any, res: any) => {
  const { id } = req.auth
  const { rewardId } = req.query
  try {
    const sql = `CALL ExChange(${id},${rewardId});`
    const [sqlres] = await db.executeResults(sql) as any;
    console.log(sqlres)
    if (sqlres.affectedRows !== undefined) {
      res.send({
        code: sqlres.affectedRows ? 200 : 201,
        message: '',
        data: !!sqlres.affectedRows,
      })
    } else {
      res.send({
        code: 201,
        message: 'mmb不足以兑换',
        data: null,
      })
    }
  } catch (e) {
    res.send({
      code: 201,
      message: e,
      data: null,
    })
  }
})
export default router
